package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.base.framework.util.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.Result;
import com.ldk.admin.constants.SESSION;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.entity.AdminUser;
import com.ldk.framework.entity.User;
import com.ldk.framework.enums.RechargeFrom;
import com.ldk.framework.enums.RechargeType;
import com.ldk.framework.service.IUserService;


@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	/**
	 * 路由地址
	 */
	private final String route = "user";
	/**
	 * 模块名称
	 */
	private final String module = "用户";
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, "", "", module+"管理", "/"+route+"/list", "", "");

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(),Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if(this.getRoleId(request) == 6) {
			return new ModelAndView("/" + route + "/listuser_sj");
		}else{
			return new ModelAndView("/" + route + "/listuser");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<User> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									       @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									       @RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
									       HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		User query = new User();
		if(!StringUtils.isEmpty(searchKey)){
			query.setSearchKey(searchKey);
		}
		String areaName = this.getAdminAreaName(request);
		if (areaName != null && areaName != "") {
			query.setSearchAreaKey(areaName);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		
		long total = userService.selectCount("", query);
		List<User> result = userService.selectList("", query, pageable);
		
		LigerUIGridResult<User> grid = new LigerUIGridResult<>();
		grid.Total = total;
		grid.Rows = result;

		// 生成8位固定ID号
		/*
		List<User>  list = userService.selectAll("");
		for(int i=0;i<list.size();i++) {
			long uCommonId = userService.generateUCommonId();

			User entity = new User();
			entity.setUserId(list.get(i).getUserId());
			entity.setuCommonId(uCommonId);

			int row = userService.updateByKey("", entity);
		}
		*/
		return grid;
	}
	
	@RequestMapping("/recharge")
	//public ModelAndView recharge(@RequestParam(value="phoneNo",required=false,defaultValue="") String phoneNo, ModelMap map)
	public ModelAndView recharge(@RequestParam(value="phoneNo",required=false,defaultValue="") String phoneNo, ModelMap map,
								 HttpServletRequest request, HttpServletResponse response)
	{
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", module +"充值", "/"+route+"/recharge?phoneNo="+phoneNo, "", "");
		map.addAttribute("phoneNo", phoneNo);

		//操作日志
		this.insertOplog(request,module +"充值","","","充值",this.getAdminUserName(request).toString(),
				Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
		
		return new ModelAndView("/"+route+"/recharge");
	}
	
	@ResponseBody
	@RequestMapping("/submitRecharge")
	public Result submitRecharge(@RequestParam(value="phoneNo",required=true,defaultValue="") String phoneNo,
						         @RequestParam(value="balance",required=true,defaultValue="0") double balance,
						         HttpServletRequest request)
	{

		Result rst = new Result();
		AdminUser admin = (AdminUser)request.getSession().getAttribute(SESSION.USER);
		if(admin == null){
			rst.AddError("登录用户已过期，请重新登录");
		}
		if(StringUtils.isEmpty(phoneNo)){
			rst.AddError("手机号不能空");
			return rst;
		}
		if(balance <= 0){
			rst.AddError("请输入充值金额");
			return rst;
		}
		User query = new User();
		query.setPhoneNo(phoneNo);
		query.setEnabled(true);
		
		User user = userService.selectOne("", query);
		if(user == null){
			rst.AddError("用户不存在");
			return rst;
		}
		Boolean succeed = false;
		try{
			//操作日志
			this.insertOplog(request,module,"","","充值:"+user.getPhoneNo(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
			succeed = userService.recharge("", phoneNo, balance, RechargeType.Cash.getValue(), RechargeFrom.FROM_ADMIN.getValue(), admin.getTrueName());
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(succeed){
			rst.AddOk("充值成功");
		}
		else{
			rst.AddError("充值失败");
		}
		return rst;
	}
	
	
}
